<!--<template>-->
<!--  <div>-->
<!--    <div class="card" style="margin-bottom: 5px">-->
<!--      <el-input v-model="data.title" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入公告标题查询"></el-input>-->
<!--      <el-button type="info" plain @click="load">查询</el-button>-->
<!--      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>-->
<!--    </div>-->
<!--    <div class="card" style="margin-bottom: 5px">-->
<!--      <el-button type="primary" plain @click="handleAdd">新增</el-button>-->
<!--      <el-button type="danger" plain @click="delBatch">批量删除</el-button>-->
<!--    </div>-->

<!--    <div class="card" style="margin-bottom: 5px">-->
<!--      <el-table stripe :data="data.tableData" @selection-change="handleSelectionChange">-->
<!--        <el-table-column type="selection" width="55" />-->
<!--        <el-table-column prop="title" label="公告标题" />-->
<!--        <el-table-column prop="content" label="公告内容" />-->
<!--        <el-table-column prop="time" label="发布时间" />-->
<!--        <el-table-column label="操作" width="100" fixed="right">-->
<!--          <template v-slot="scope">-->
<!--            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>-->
<!--            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--      </el-table>-->
<!--    </div>-->
<!--    <div class="card" v-if="data.total">-->
<!--      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />-->
<!--    </div>-->

<!--    <el-dialog title="公告信息" v-model="data.formVisible" width="40%" destroy-on-close>-->
<!--      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">-->
<!--        <el-form-item prop="title" label="公告标题">-->
<!--          <el-input v-model="data.form.title" placeholder="请输入公告标题"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item prop="content" label="公告内容">-->
<!--          <el-input type="textarea" :rows="4" v-model="data.form.content" placeholder="请输入公告内容"></el-input>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <template #footer>-->
<!--        <span class="dialog-footer">-->
<!--          <el-button @click="data.formVisible = false">取 消</el-button>-->
<!--          <el-button type="primary" @click="save">确 定</el-button>-->
<!--        </span>-->
<!--      </template>-->
<!--    </el-dialog>-->
<!--  </div>-->
<!--</template>-->

<!--<script setup>-->

<!--import {reactive} from "vue";-->
<!--import request from "@/utils/request.js";-->
<!--import {ElMessage, ElMessageBox} from "element-plus";-->
<!--import {Delete, Edit} from "@element-plus/icons-vue";-->


<!--const data = reactive({-->
<!--  formVisible: false,-->
<!--  form: {},-->
<!--  tableData: [],-->
<!--  pageNum: 1,-->
<!--  pageSize: 10,-->
<!--  total: 0,-->
<!--  title: null,-->
<!--  ids: []-->
<!--})-->

<!--const load = () => {-->
<!--  request.get('/notice/selectPage', {-->
<!--    params: {-->
<!--      pageNum: data.pageNum,-->
<!--      pageSize: data.pageSize,-->
<!--      title: data.title-->
<!--    }-->
<!--  }).then(res => {-->
<!--    if (res.code === '200') {-->
<!--      data.tableData = res.data?.list || []-->
<!--      data.total = res.data?.total-->
<!--    }-->
<!--  })-->
<!--}-->
<!--const handleAdd = () => {-->
<!--  data.form = {}-->
<!--  data.formVisible = true-->
<!--}-->
<!--const handleEdit = (row) => {-->
<!--  data.form = JSON.parse(JSON.stringify(row))-->
<!--  data.formVisible = true-->
<!--}-->
<!--const add = () => {-->
<!--  request.post('/notice/add', data.form).then(res => {-->
<!--    if (res.code === '200') {-->
<!--      ElMessage.success('操作成功')-->
<!--      data.formVisible = false-->
<!--      load()-->
<!--    } else {-->
<!--      ElMessage.error(res.msg)-->
<!--    }-->
<!--  })-->
<!--}-->

<!--const update = () => {-->
<!--  request.put('/notice/update', data.form).then(res => {-->
<!--    if (res.code === '200') {-->
<!--      ElMessage.success('操作成功')-->
<!--      data.formVisible = false-->
<!--      load()-->
<!--    } else {-->
<!--      ElMessage.error(res.msg)-->
<!--    }-->
<!--  })-->
<!--}-->

<!--const save = () => {-->
<!--  data.form.id ? update() : add()-->
<!--}-->

<!--const del = (id) => {-->
<!--  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {-->
<!--    request.delete('/notice/delete/' + id).then(res => {-->
<!--      if (res.code === '200') {-->
<!--        ElMessage.success("删除成功")-->
<!--        load()-->
<!--      } else {-->
<!--        ElMessage.error(res.msg)-->
<!--      }-->
<!--    })-->
<!--  }).catch(err => {-->
<!--    console.error(err)-->
<!--  })-->
<!--}-->
<!--const delBatch = () => {-->
<!--  if (!data.ids.length) {-->
<!--    ElMessage.warning("请选择数据")-->
<!--    return-->
<!--  }-->
<!--  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', { type: 'warning' }).then(res => {-->
<!--    request.delete("/notice/delete/batch", {data: data.ids}).then(res => {-->
<!--      if (res.code === '200') {-->
<!--        ElMessage.success('操作成功')-->
<!--        load()-->
<!--      } else {-->
<!--        ElMessage.error(res.msg)-->
<!--      }-->
<!--    })-->
<!--  }).catch(err => {-->
<!--    console.error(err)-->
<!--  })-->
<!--}-->
<!--const handleSelectionChange = (rows) => {-->
<!--  data.ids = rows.map(v => v.id)-->
<!--}-->

<!--const reset = () => {-->
<!--  data.title = null-->
<!--  load()-->
<!--}-->

<!--load()-->
<!--</script>-->
<template>
  <div>
    <!-- 搜索和重置按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.title" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入公告标题查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <!-- 新增和批量删除按钮 -->
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <!-- 表格展示公告信息及附件 -->
    <div class="card" style="margin-bottom: 5px">
      <el-table stripe :data="data.tableData" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="公告标题" />
        <el-table-column prop="content" label="公告内容" />
        <el-table-column prop="time" label="发布时间" />
        <el-table-column label="附件" width="150">
          <template v-slot="scope">
            <!-- 显示附件链接 -->
            <a v-if="scope.row.attachment" :href="scope.row.attachment" target="_blank">下载附件</a>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页组件 -->
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <!-- 新增/编辑公告对话框 -->
    <el-dialog title="公告信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="title" label="公告标题">
          <el-input v-model="data.form.title" placeholder="请输入公告标题"></el-input>
        </el-form-item>
        <el-form-item prop="content" label="公告内容">
          <el-input type="textarea" :rows="4" v-model="data.form.content" placeholder="请输入公告内容"></el-input>
        </el-form-item>
        <el-form-item label="附件">
          <el-upload
              class="upload-demo"
              ref="upload"
              :action="uploadUrl"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :on-success="handleSuccess"
              :on-error="handleError"
              :limit="1"
              :accept="'.zip,.rar'">
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
          <span v-if="data.form.attachment" class="attachment-name">{{ data.form.attachment }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit } from "@element-plus/icons-vue";

const data = reactive({
  formVisible: false,
  form: { attachment: "" },  // 将附件初始化为字符串
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  title: null,
  ids: [],
});

const uploadUrl = import.meta.env.VITE_BASE_URL + "/files/upload"; // 上传文件的接口URL

// 查询公告
const load = () => {
  request.get("/notice/selectPage", {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      title: data.title,
    },
  }).then((res) => {
    if (res.code === "200") {
      data.tableData = res.data?.list || [];
      data.total = res.data?.total;
    }
  });
};

// 新增按钮
const handleAdd = () => {
  data.form = { attachment: "" }; // 清空表单
  data.formVisible = true; // 打开表单对话框
};

// 编辑按钮
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row)); // 深拷贝数据
  data.formVisible = true; // 打开表单对话框
};

// 保存数据
const save = () => {
  data.form.id ? update() : add();
};

// 添加公告
const add = () => {
  request.post("/notice/add", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 更新公告
const update = () => {
  request.put("/notice/update", data.form).then((res) => {
    if (res.code === "200") {
      ElMessage.success("操作成功");
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 删除公告
const del = (id) => {
  ElMessageBox.confirm("删除后数据无法恢复，您确定删除吗？", "删除确认", {
    type: "warning",
  }).then(() => {
    request.delete("/notice/delete/" + id).then((res) => {
      if (res.code === "200") {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};

// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm("删除后数据无法恢复，您确定删除吗？", "删除确认", {
    type: "warning",
  }).then(() => {
    request.delete("/notice/delete/batch", { data: data.ids }).then((res) => {
      if (res.code === "200") {
        ElMessage.success("操作成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  });
};

// 表格选择变化
const handleSelectionChange = (rows) => {
  data.ids = rows.map((v) => v.id);
};

// 重置查询条件
const reset = () => {
  data.title = null;
  load();
};

// 上传前检查文件类型
const beforeUpload = (file) => {
  const isValidType = file.type === "application/x-zip-compressed" || file.type === "application/rar";
  if (!isValidType) {
    ElMessage.error("只能上传zip或rar格式的文件");
  }
  return isValidType;
};

// 上传成功后处理
const handleSuccess = (response, file) => {
  if (response && response.data) {
    data.form.attachment = response.data;  // 保存返回的文件URL
    ElMessage.success("附件上传成功");
  } else {
    ElMessage.error("附件上传失败");
  }
};

// 上传失败后处理
const handleError = (err, file) => {
  ElMessage.error("附件上传失败");
};

load();
</script>
